<?php
/**
 * Created by PhpStorm.
 * User: Dave
 * Date: 2018/8/23
 * Time: 19:40
 */

namespace Biz\model\activity;

use Doraemon\pockets\datebase\BaseDbModel;
use Doraemon\tools\ImgUrl as toolImgUrl;
use Biz\tools\Link as tLink;

class ActivityMeal extends BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_activity';

    const _DATABASE_ = 'shop_activity';

    const _TABLE_NAME = 'activity_meal';

    const STATUS_NORMAL = 1;
    const STATUS_START = 2;
    const STATUS_NOT_START = 3;
    const STATUS_END = 4;
    const STATUS_DELETE = 9;

    const STATUS_DESC = [
        self::STATUS_NORMAL => '正常',
        self::STATUS_START => '进行中',
        self::STATUS_NOT_START => '未开始',
        self::STATUS_END => '已结束',
        self::STATUS_DELETE => '已删除',
    ];



    public static function addActivityMeal($post)
    {
        if(self::insert($post)->rowcount()) {
            return self::id();
        }
    }

    public static function updateActivityMeal($mealId, $post)
    {
        $mealId  = self::get('meal_id', ['meal_id' => $mealId]);

        if($mealId) {
            $result = self::update($post, ['meal_id' => $mealId]);
        } else {
            $post['addtime'] = date('Y-m-d H:i:s');
            $result = self::insert($post);
            $mealId = self::id();
        }

        if ($result->errorCode() !== '00000') {
            throw new \Exception('操作失败,请重试');
        }

        return $mealId;
    }

    public static function updateStatus($mealId, $status)
    {
        $result = self::update(['status' => $status, 'real_end_time' => date('Y-m-d H:i:s')], ['meal_id' => $mealId]);

        if ($result->errorCode() !== '00000') {
            throw new \Exception('操作失败,请重试');
        }

        return $mealId;
    }

    public static function admGetActivityMealById($mealId, $isFormat = false)
    {
       $activityMeal  = self::get('*', ['meal_id' => $mealId]);
       if($activityMeal && $isFormat) {
           self::admFormatActivityMeal($activityMeal);
       }

       return $activityMeal;
    }

    public static function admGetActivityMealByShopId($shopId, $limit, $isFormat = false)
    {
        $list = [];
        $activityMeal  = self::select('*', [
            'AND' => [
                'shop_id' => $shopId,
                'status' => [self::STATUS_NORMAL,self::STATUS_END],
            ],
            'LIMIT' => $limit,
            'ORDER' => ['sort' => 'DESC', 'meal_id' => 'DESC']
        ]);

        if($activityMeal && $isFormat) {
            foreach ($activityMeal as $info)
            {
                self::admFormatActivityMeal($info);
                $list[$info['meal_id']] = $info;
            }

        }

        return $list;
    }

    public static function admGetActivityMealCountByShopId($shopId)
    {
        $mealCount = self::count('*', [
            'AND' => [
                'shop_id' => $shopId,
                'status' => [self::STATUS_NORMAL,self::STATUS_END],
            ]
        ]);

        return $mealCount ? : 0;
    }

    public static function getMealListByShopId($shopId, $field = '*')
    {
        $time = date('Y-m-d H:i:s');
        $mealList = self::select($field, [
            'AND' => [
                'shop_id' => $shopId,
                'status' => self::STATUS_NORMAL,
                'start_time[<=]' => $time,
                'end_time[>=]' => $time,
            ],
            'ORDER' => ['sort' => 'DESC', 'meal_id' => 'DESC'],
        ]);

        return $mealList;
    }

    public static function getMealInfoByMealId($mealId, $field = '*')
    {
        $time = date('Y-m-d H:i:s');
        $info = self::get($field, [
            'AND' => [
                'meal_id' => $mealId,
                'status' => [self::STATUS_NORMAL],
                'start_time[<=]' => $time,
                'end_time[>=]' => $time,
            ]
        ]);

        return $info;
    }

    public static function getMealByMealIds($mealIds, $field = '*')
    {
        $meal = self::select($field, [
            'AND' => [
                'meal_id' => $mealIds,
                'status' => self::STATUS_NORMAL,
            ]
        ]);
        $meal = array_column($meal, null, 'meal_id');
        return $meal;
    }

    public static function getMaxSort()
    {
        return self::max('sort', [
            'status' => [self::STATUS_NORMAL, self::STATUS_END]
        ]);
    }

    public static function setTop($mealId, $sort = 0)
    {
        $result = self::update(['sort' => $sort], ['meal_id' => $mealId]);

        if ($result->errorCode() !== '00000') {
            throw new \Exception('操作失败,请重试');
        }

        return $mealId;
    }

    private static function admFormatActivityMeal(&$info)
    {
        foreach ($info as $key => $value)
        {
            switch ($key) {
                case 'meal_img_info' :
                    if($value) {
                        $value = json_decode($value, true);
                        $info['meal_img_info'] = array_map(function ($v) {
                            $data = [
                                'hash' => $v['img'],
                                'img' => toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $v['img'],
                                    toolImgUrl::IMAGE_SIZE_ORI_NPHONE),
                                'link' => $v['link'],
                                'link_type' => $v['link_type'],
                            ];
                            return $data;
                        }, $value);
                    } else {
                        $info['meal_img_info'] = [];
                    }
                    break;
                case 'tags' :
                        if($value) {
                            $value = json_decode($value);
                        }
                        $info['tags'] = $value ? : [];
                    break;
                case 'end_time' :
                    if(strtotime($value) < time()) {
                        $info['status'] = self::STATUS_END;
                        $info['status_desc'] = self::STATUS_DESC[self::STATUS_END];
                    }elseif(strtotime($value) > time() && strtotime($info['start_time']) < time()) {
                        $info['status'] = self::STATUS_START;
                        $info['status_desc'] = self::STATUS_DESC[self::STATUS_START];
                    } else {
                        $info['status_desc'] = self::STATUS_DESC[$info['status']];
                    }
                    break;
                case 'start_time' :
                    if(strtotime($value) > time()) {
                        $info['status'] = self::STATUS_NOT_START;
                        $info['status_desc'] = self::STATUS_DESC[self::STATUS_NOT_START];
                    }
                    break;
                case 'real_end_time' :
                    if($value != '0000-00-00 00:00:00') {
                        $info['status'] = self::STATUS_END;
                        $info['status_desc'] = self::STATUS_DESC[self::STATUS_END];
                    }
                    break;
                case 'cover_img' :
                    $info['cover_img'] = [
                        'hash' => $value,
                        'url' => toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $value, toolImgUrl::IMAGE_SIZE_ORI_NPHONE)
                    ];
                    break;
            }
        }
    }

    public static function formatActivityMeal(&$info)
    {
        foreach ($info as $key => $value)
        {
            switch ($key) {

                case 'meal_img_info' :
                    if($value) {
                        $value = json_decode($value, true);
                        $info['meal_img_info'] = array_map(function ($v) {
                            $data['img'] = toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $v['img'],
                                toolImgUrl::IMAGE_SIZE_ORI_NPHONE);
                            $data['inner_link'] = tLink::format($v['link_type'], $v['link']);
                            $data['outer_link'] = $v['link'];
                            $data['link_type'] = $v['link_type'];
                            return $data;
                        }, $value);
                    } else {
                        $info['meal_img_info'] = [];
                    }
                    break;
                case 'tags' :
                    if($value) {
                        $value = json_decode($value, true);
                    }
                    $info['tags'] = $value ? : [];
                    break;
                case 'cover_img' :
                    $info['cover_img'] = toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ, $value, toolImgUrl::IMAGE_SIZE_ORI_NPHONE);
                    break;
            }
        }
    }
}